<?php

namespace app\api\controller\meet;

use app\common\controller\Api;
use app\common\model\meet\Config;
use app\common\model\meet\Coupon;
use app\common\model\meet\CouponTemplate;
use app\common\model\meet\OrderImages;
use app\common\model\meet\Store;
use EasyWeChat\Factory;


class Order extends Api
{
    protected $noNeedLogin = ['notify'];
    protected $noNeedRight = ['*'];


    public function index()
    {
        $page = $this->request->get('page/d', 1);
        $page_size = $this->request->get('page_size/d', 10);
        $status = $this->request->get('status/d', 0);

        $condition = [
            'user_id' => $this->auth->id
        ];

        if (!empty($status)) {
            $condition['order_status'] = $status;
        }

        $model = new \app\common\model\meet\Order();

        $list = $model->with('products')->where($condition)->order('createtime', 'desc')->paginate(['list_rows' => $page_size, 'page' => $page]);

        if ($list->items()) {

            foreach ($list as $key => $value) {
                if ($value['order_status'] == $model::ORDER_STATUS_PAYED) {
                    $store = Store::where('id', $value['store_id'])->field('id,early_refund,refund_handle_fee')->find();

                    $value['refund_handle_fee'] = $store['refund_handle_fee'];
                }
            }
        }


        $this->success('', $list);
    }

    public function orderImages()
    {
        $order_id = $this->request->get('order_id/d', 0);

        if (empty($order_id)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $model = new OrderImages();

        $list = $model->where('order_id', $order_id)->field('id,image,order_id')->order('id', 'desc')->select();

        $this->success('', ['list' => $list]);
    }

    public function generateOrderInfo()
    {
        $product_id = $this->request->get('product_id/d', 0);
        $product_sku_id = $this->request->get('product_sku_id', '');
        $reservation_time = $this->request->get('reservation_time', '');
        $coupon_id = $this->request->get('coupon_id/d', 0);

        $orderLogic = new \app\common\logic\meet\Order();

        $order = $orderLogic->getOrderData($this->auth->id, $product_id, $product_sku_id, $reservation_time, $coupon_id);

        if (!$order) {
            $this->error($orderLogic->getError());
        }

        $this->success('', $order);
    }

    public function getCouponList()
    {
        $limit = $this->request->get('limit', '');
        $product_ids = $this->request->get('product_ids', '');

        $model = new Coupon();

        $condition = [
            'status' => $model::STATUS_NOT_USE,
            'user_id' => $this->auth->id,
            'end_time' => ['gt', time()],
            'limit' => ['elt', $limit]
        ];

        $orCondition = [
            'status' => $model::STATUS_NOT_USE,
            'user_id' => $this->auth->id,
            'end_time' => 0,//无期限
            'limit' => ['elt', $limit]
        ];

//        if (!empty($limit)) {
//            $condition['limit'] = ['elt', $limit];
//            $condition['start_time'] = ['elt', time()];
//            $orCondition['limit'] = ['elt', $limit];
//        }

        $list = $model
            ->where(function ($query) use ($condition) {
                $query->where($condition);
            })
            ->whereOr(function ($query) use ($orCondition) {
                $query->where($orCondition);
            })
            ->order('createtime', 'desc')
            ->select();

        $new_list = [];

        if ($list) {
            $product_ids_arr = $product_ids ? explode(',', $product_ids) : [];
            foreach ($list as $key => $value) {
                if ($value['available_type'] === CouponTemplate::AVAILABLE_TYPE_MALL) {
                    continue;
                }

                if ($value['range_type'] === CouponTemplate::RANGE_TYPE_APPOINT) {
                    $range_reservation_arr = explode(',', $value['range_reservation']);
                    $intersect = array_intersect($range_reservation_arr, $product_ids_arr);

                    if (empty($intersect)) {
                        continue;
                    }
                }

                $validity = '';

                $range = '';

                if ($value['status'] == $model::STATUS_NOT_USE) {
                    if (!empty($value['start_time'])) {
                        $validity = date('Y-m-d', $value['end_time']) . ' 前有效';
                    } else {
                        $validity = '未使用前永久有效';
                    }
                }

                if ($value['available_type'] === CouponTemplate::AVAILABLE_TYPE_MALL) {
                    $range = '仅限购买商品使用';
                } else if ($value['available_type'] === CouponTemplate::AVAILABLE_TYPE_RESERVATION) {
                    $range = '仅限预约使用';
                } else if ($value['available_type'] === CouponTemplate::AVAILABLE_TYPE_ALL) {
                    $range = '全场通用';
                }

                $value['range'] = $range;

                $value['validity'] = $validity;

                $new_list[] = $value;
            }
        }

        $this->success('', ['list' => $new_list]);
    }

    public function submit()
    {
        $post = $this->request->post();

        if (empty($post)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        if (empty($post['call_name']) || $post['gender'] === '') {
            $this->error(__("Please fill in the photographer's information"));
        }

        $orderLogic = new \app\common\logic\meet\Order();

        $order = $orderLogic->getOrderData($this->auth->id, $post['product_id'], $post['product_sku_id'], $post['reservation_time'], $post['coupon_id']);

        if (!$order) {
            $this->error($orderLogic->getError());
        }

        $result = $orderLogic->createOrder($this->auth->getUserinfo(), $order, $post);

        if (!$result) {
            $this->error($orderLogic->getError());
        }

        $this->success('', ['order_id' => $result]);
    }

    public function pay()
    {
        $order_id = $this->request->post('order_id/d', 0);

        if (empty($order_id)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $orderLogic = new \app\common\logic\meet\Order();

        $notify_url = $this->request->root(true) . '/api/meet.order/notify';

        $result = $orderLogic->payOrder($order_id, $notify_url);

        if (!$result) {
            $this->error($orderLogic->getError());
        }

        $this->success('', $result);
    }

    public function cancel()
    {
        $order_id = $this->request->post('order_id/d', 0);

        if (empty($order_id)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $orderLogic = new \app\common\logic\meet\Order();

        $result = $orderLogic->cancelOrder($order_id);

        if (!$result) {
            $this->error($orderLogic->getError());
        }

        //删除定时取消任务
        (new \app\common\model\meet\Cron())->where(['event' => 'CronMeetOrderCancel', 'relate_id' => $order_id])->delete();

        $this->success(__('Operation completed'));
    }

    public function complete()
    {
        $order_id = $this->request->post('order_id/d', 0);

        if (empty($order_id)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $orderLogic = new \app\common\logic\meet\Order();

        $result = $orderLogic->completeOrder($order_id);

        if (!$result) {
            $this->error($orderLogic->getError());
        }

        //删除订单完成任务
//        (new \app\common\model\meet\Cron())->where(['event' => 'CronMeetOrderComplete', 'relate_id' => $order_id])->delete();

        $this->success(__('Operation completed'));
    }

    public function refund()
    {
        $order_id = $this->request->post('order_id/d', 0);

        if (empty($order_id)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $orderLogic = new \app\common\logic\meet\Order();

        $result = $orderLogic->refundOrder($order_id);

        if (!$result) {
            $this->error($orderLogic->getError());
        }

        $this->success(__('Operation completed'));
    }

    public function notify()
    {
        $config = Config::getPayConfig();

        $app = Factory::payment($config);

        $response = $app->handlePaidNotify(function ($message, $fail) {
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    //商户订单号
                    $out_trade_no = $message['out_trade_no'];
                    //微信支付订单号
                    $transaction_id = $message['transaction_id'];

                    $model = new \app\common\model\meet\Order();

                    $order_info = $model->where('order_no', '=', $out_trade_no)->find();

                    if (empty($order_info)) {
                        //订单不存，订单不做处理，通知微信处理完成。
                        return true;
                    }

                    if ($order_info['pay_status'] == $model::PAY_STATUS_PAYED) {
                        //订单支付状态，订单不做处理，通知微信处理完成。
                        return true;
                    }

                    $orderLogic = new \app\common\logic\meet\Order();

                    $update = [
                        'transaction_id' => $transaction_id,
                    ];

                    $orderLogic->paySuccess($order_info, $update, 'wxapp');

                } elseif ($message['result_code'] === 'FAIL') {
                    // 用户支付失败
                    return true; // 返回处理完成
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }

            return true; // 返回处理完成
        });

        $response->send();
    }
}
